package org.zhengquan.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.zhengquan.exception.ParamException;
import org.zhengquan.exception.PermissionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhengquan
 * @date 2017/10/26
 */
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {

    private final String ENDWITH_JSON = ".json";
    private final String ENDWITH_PAGE = ".page";

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String url = httpServletRequest.getRequestURL().toString();
        ModelAndView mv = null;
        String defalutMsg = "System error!";

        //.json .page
        //这里要求项目中所有请求json数据的请求都使用.json结尾,page数据都使用.page结尾
        if (url.endsWith(ENDWITH_JSON)) {
            if (e instanceof PermissionException ||e instanceof ParamException) {
                JsonData jsonData = JsonData.fail(e.getMessage());
                mv = new ModelAndView("jsonView", jsonData.toMap());
            } else {
                log.error("unknow json exception url:" + url, e);
                JsonData jsonData = JsonData.fail(defalutMsg);
                mv = new ModelAndView("jsonView", jsonData.toMap());
            }
        } else if (url.endsWith(ENDWITH_PAGE)) {
            log.error("unknow page exception url:" + url, e);
            JsonData jsonData = JsonData.fail(defalutMsg);
            mv = new ModelAndView("exception", jsonData.toMap());
        } else {
            log.error("unknow common exception url:" + url, e);
            JsonData jsonData = JsonData.fail(defalutMsg);
            mv = new ModelAndView("jsonView", jsonData.toMap());
        }
        return mv;
    }
}
